import axios from 'axios'
import { CustomAxiosRequestConfig } from '@/type/api'

import { targetUrl } from '@/utils/config'

const instance = axios.create({
  baseURL: targetUrl,
  timeout: 20000
})

// 请求拦截器
instance.interceptors.request.use(
  config => {
    const customConfig: CustomAxiosRequestConfig = config
    if (customConfig.port) {
      if (config.baseURL) {
        console.log(config.baseURL)
        // const i: number = config.baseURL.lastIndexOf(':')
        // const newURL = config.baseURL.substring(0, i) + ':' + customConfig.port
        config.baseURL = config.baseURL + ':' + customConfig.port
      }
    } else {
      config.baseURL = targetUrl + ':8887'
    }
    console.log(config.baseURL)
    config.headers['Authorization'] = 'Bearer ' + localStorage.getItem('token')
    return config
  },
  err => {
    return Promise.reject(err)
  }
)

// 响应拦截器
instance.interceptors.response.use(
  res => {
    return res.data
  },
  err => {
    return Promise.reject(err)
  }
)

export default instance
